# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)

# helper ----
source('../00_custom_functions.R')

# data ----
state <- "AL"

ppmf19 <- read_ppmf(state, "../../data-raw/ppmf_19.csv")
ppmf12 <- read_ppmf(state, "../../data-raw/ppmf_12.csv")
ppmf4 <- read_ppmf(state, "../../data-raw/ppmf_04.csv")

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf19) <- paste("v19", colnames(ppmf19), sep = "_")
ppmf19 <- ppmf19 %>% rename(GEOID = v19_GEOID)

ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf12) <- paste("v12", colnames(ppmf12), sep = "_")
ppmf12 <- ppmf12 %>% rename(GEOID = v12_GEOID)

ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf4) <- paste("v4", colnames(ppmf4), sep = "_")
ppmf4 <- ppmf4 %>% rename(GEOID = v4_GEOID)

# comparison ----
census <- create_block_table(state = state)

# all joined ----
mega <- census %>%
  left_join(ppmf12, by = 'GEOID') %>%
  left_join(ppmf4, by = 'GEOID') %>%
  left_join(ppmf19, by = "GEOID")

# and remove duplicates
mega <- mega %>% select(-contains('.'))

# and set missing block pop/vap to 0
mega[is.na(mega)] <- 0

# add block_group back (dropped by contains('.'))
mega <- mega %>% breakdown_geoid()

# Get Census Shapes :
sld_low <- tigris::state_legislative_districts(state, 'lower')
sld_up <- tigris::state_legislative_districts(state, 'upper')
cd <- tigris::congressional_districts(state)

# VEST 2018
prec <- st_read('../../data/AL/al_2018/al_2018.shp')


# Align ppmf & precincts:
sf::sf_use_s2(FALSE)
block_prec_match <- geo_match(from = mega, to = prec, method = 'area')
prec_low_match <- geo_match(from = prec, to = sld_low, method = 'area')
prec_up_match <- geo_match(from = prec, to = sld_up, method = 'area')
prec_cd_match <- geo_match(from = prec, to = cd, method = 'area')

prec <- prec %>% mutate(
  sld_low = sld_low$SLDLST[prec_low_match],
  sld_up = sld_up$SLDUST[prec_up_match],
  cd = cd$CD116FP[prec_cd_match]
)

mega$prec <- block_prec_match
ppmf_at_prec <- ppmf_block2prec(mega, prec)

# compute parities:
block_cd_match <- geo_match(from = mega, to = cd, method = 'area')
redist.parity(block_cd_match, mega$pop)
# 0.0003784728
block_low_match <- geo_match(from = mega, to = sld_low, method = 'area')
redist.parity(block_low_match, mega$pop)
# 0.01008968
block_up_match <- geo_match(from = mega, to = sld_up, method = 'area')
redist.parity(block_up_match, mega$pop)
# 0.009944901

# join them together
al <- prec %>%
  mutate(prec = row_number()) %>%
  left_join(ppmf_at_prec, by = 'prec')

al$cd <- as.numeric(al$cd)
al$sld_low <- as.numeric(al$sld_low)
al$sld_up <- as.numeric(al$sld_up)
al <- al %>% mutate(row_id = row_number())
saveRDS(al, '../../data/AL/al.Rds')

